<template>
  <div>
    <div>
      <i class="el-icon-s-promotion" style="color: #2989FF;" />
      机构信息
      <br>
      <br>

      <div class="container">
        <!-- 总营业额卡片 -->
        <div style="width: 20%; height: 80px; display: flex; align-items: center; margin-top: 10px;
    background-color: white; border-radius: 8px; box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);">
          <div style="display: flex; justify-content: flex-start; margin-right: 10px;">
            <i class="el-icon-s-finance" style="color: green; font-size: 40px;"></i>
          </div>
          <div>
            <label style="margin-left: 10px; font-size: 18px;">总营业额</label>
            <hr style="margin-top: 10px; border-color: #e2e2e2; background-color: #2989FF;">
            <label style="display: flex; align-items: center; justify-content: center; font-size: 18px;">
              ¥ {{ this.allMoney }}
            </label>
          </div>
        </div>

        <!-- 今日订单数卡片 -->
        <div style="width: 20%; height: 80px; display: flex; align-items: center; margin-top: 10px;
    background-color: white; border-radius: 8px; box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);">
          <div style="display: flex; justify-content: flex-start; margin-right: 10px;">
            <i class="el-icon-s-order" style="color: blue; font-size: 40px;"></i>
          </div>
          <div>
            <label style="margin-left: 10px; font-size: 18px;">今日订单数</label>
            <hr style="margin-top: 10px; border-color: #e2e2e2; background-color: #2989FF;">
            <label style="display: flex; align-items: center; justify-content: center; font-size: 18px;">
              {{ this.todayOrder}}
            </label>
          </div>
        </div>

        <!-- 今日营业额卡片 -->
        <div style="width: 20%; height: 80px; display: flex; align-items: center; margin-top: 10px;
    background-color: white; border-radius: 8px; box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);">
          <div style="display: flex; justify-content: flex-start; margin-right: 10px;">
            <i class="el-icon-money" style="color: red; font-size: 40px;"></i>
          </div>
          <div>
            <label style="margin-left: 10px; font-size: 18px;">今日营业额</label>
            <hr style="margin-top: 10px; border-color: #e2e2e2; background-color: #2989FF;">
            <label style="display: flex; align-items: center; justify-content: center; font-size: 18px;">
              ¥ {{ this.todayMoney }}
            </label>
          </div>
        </div>
      </div>

      <br>
      <i class="el-icon-s-order" style="color: #2989FF" />
      <label>我的工单</label>
      <br>
      <br>
      <div style="display: flex; justify-content: space-between; flex-wrap: wrap; margin-top: 20px;">
        <el-table :data="tableData" border style="width: 48%; margin-right: 10px;">
          <el-table-column prop="createdAt" label="下单时间" width="150" :formatter="formatDate"></el-table-column>
          <el-table-column prop="name" label="姓名" width="100"></el-table-column>
          <el-table-column prop="servicename" label="服务名称" width="100"></el-table-column>
          <el-table-column prop="status" label="当前状态" width="100" :formatter="getStatusLabel"></el-table-column>
          <el-table-column prop="paymentMethod" label="支付方式" width="100"></el-table-column>
          <el-table-column fixed="right" label="操作" width="100">
            <template slot-scope="scope">
              <el-button @click="openDialog(scope.row)" type="text" size="small">派送订单</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-table :data="tableData1" border style="width: 48%;">
          <el-table-column prop="createdAt" label="下单时间" width="150" :formatter="formatDate"></el-table-column>
          <el-table-column prop="name" label="姓名" width="90"></el-table-column>
          <el-table-column prop="servicename" label="服务名称" width="120"></el-table-column>
          <el-table-column prop="status" label="当前状态" width="100" :formatter="getStatusLabel"></el-table-column>
          <el-table-column prop="paymentMethod" label="支付方式" width="90"></el-table-column>
          <el-table-column fixed="right" label="操作" width="100">
            <template slot-scope="scope">
              <el-button @click="getDetail(scope.row)" type="text" size="small">查看订单详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 员工选择对话框 -->
      <el-dialog title="选择员工服务" :visible.sync="dialogVisible" width="30%">
        <el-table :data="spareEmployees" border style="width: 100%;">
          <el-table-column prop="name" label="员工姓名" width="150"></el-table-column>
          <el-table-column prop="status" label="状态" width="120"  :formatter="getEmployeeStatus"></el-table-column>
          <el-table-column fixed="right" label="操作" width="100">
            <template slot-scope="scope">
              <el-button @click="assignEmployee(scope.row)" type="primary" size="small"
                :disabled="scope.row.status === 0 || scope.row.status === 2">派单</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>

      <el-dialog title="订单详情" :visible.sync="detailsDialogVisible" width="50%">
        <div>
          <el-row style="margin-bottom: 10px;">
            <el-col :span="8">订单 ID:</el-col>
            <el-col :span="16">{{ orderDetails.id }}</el-col>
          </el-row>
          <el-row style="margin-bottom: 10px;">
            <el-col :span="8">客户姓名:</el-col>
            <el-col :span="16">{{ orderDetails.name }}</el-col>
          </el-row>
          <el-row style="margin-bottom: 10px;">
            <el-col :span="8">员工姓名:</el-col>
            <el-col :span="16">{{ orderDetails.employeename }}</el-col>
          </el-row>
          <el-row style="margin-bottom: 10px;">
            <el-col :span="8">客户地址:</el-col>
            <el-col :span="16">{{ orderDetails.oldaddress }}</el-col>
          </el-row>
          <el-row style="margin-bottom: 10px;">
            <el-col :span="8">客户电话:</el-col>
            <el-col :span="16">{{ orderDetails.oldphone }}</el-col>
          </el-row>
          <el-row style="margin-bottom: 10px;">
            <el-col :span="8">服务名称:</el-col>
            <el-col :span="16">{{ orderDetails.servicename }}</el-col>
          </el-row>
          <el-row style="margin-bottom: 10px;">
            <el-col :span="8">支付方式:</el-col>
            <el-col :span="16">{{ orderDetails.paymentMethod }}</el-col>
          </el-row>
          <el-row style="margin-bottom: 10px;">
            <el-col :span="8">总价格:</el-col>
            <el-col :span="16">{{ orderDetails.totalPrice }}</el-col>
          </el-row>
          <el-row style="margin-bottom: 10px;">
            <el-col :span="8">订单状态:</el-col>
            <el-col :span="16">{{ getStatusLabel(orderDetails.status) }}</el-col>
          </el-row>
          <!-- <el-row style="margin-bottom: 10px;">
      <el-col :span="8">下单时间:</el-col>
      <el-col :span="16">{{ formatDate(orderDetails.createdAt) }}</el-col>
    </el-row>
    <el-row style="margin-bottom: 10px;">
      <el-col :span="8">更新时间:</el-col>
      <el-col :span="16">{{ formatDate(orderDetails.updatedAt) }}</el-col>
    </el-row> -->
        </div>
      </el-dialog>


    </div>
  </div>
</template>

<script>
import { getProcessingOrder, getAlreadyOrder, getSpareEmployee, assignOrderToEmployee, getOrderTail } from '../api/order.ts'
import { getallMoney, gettodayMoney, gettodayOrder } from '../api/login.ts'
export default {
  data() {

    return {
      dialogVisible: false,  // 初始化弹窗的显示状态
      detailsDialogVisible: false, // 初始化详情弹窗的显示状态
      spareEmployees: [],    // 用于存放空闲员工的数据
      tableData: [],         // 用于第一个表格的数据
      tableData1: [],      // 用于第二个表格的数据
      orderDetails: {
        acceptid: "",
        id: "",// 确保 id 存在，用于后端处理
        insid: "",
        name: "",
        paymentMethod: "",
        servicename: "",
        status: "",
        totalPrice: "",
        createdAt: "",
        updatedAt: "",
        userId: "",
      },
      allMoney: 0,
      todayMoney: 0,
      todayOrder: 0,
    }
  },
  created() {
    this.fetchData();
    this.getAllMoney();
    this.getTodayMoney();
    this.getTodayOrder();
  },
  mounted() {
    // 确保 DOM 渲染完成后执行 onColumnsChange
    this.$nextTick(() => {
      this.onColumnsChange();
    });
  },
  methods: {
    // 监听列的变化，确保元素已经渲染完毕
    onColumnsChange() {
      // 检查 this.$el 是否存在并且支持 querySelectorAll 方法
      if (this.$el && typeof this.$el.querySelectorAll === 'function') {
        const elements = this.$el.querySelectorAll('.your-selector');
        console.log(elements); // 执行操作
      } else {
        console.error("无法找到 DOM 元素，this.$el 可能尚未渲染");
      }
    },
    // 获取数据的方法
    async fetchData() {
      try {
        const processingOrderResponse = await getProcessingOrder();
        console.log('Processing Order Data:', processingOrderResponse.data.data); // 调试输出
        this.tableData = processingOrderResponse.data.data.map(order => ({
          ...order,
          formattedDate: this.formatDate(order.createdAt),
          statusLabel: this.getmoreStatusLabel(order.status)
        }));

        const alreadyOrderResponse = await getAlreadyOrder();
        console.log('Already Order Data:', alreadyOrderResponse.data.data); // 调试输出
        this.tableData1 = alreadyOrderResponse.data.data.map(order => ({
          ...order,
          formattedDate: this.formatDate(order.createdAt),
          statusLabel: this.getmoreStatusLabel(order.status)
        }));
      } catch (error) {
        console.error("获取订单数据失败：", error);
      }
    },
    async getDetail(row) {

      try {
        // 创建包含所有需要数据的 order 对象
        const order = {
          acceptid: row.acceptid,
          id: row.id,  // 确保 id 存在，用于后端处理
          insid: row.insid,
          name: row.name,
          paymentMethod: row.paymentMethod,
          servicename: row.servicename,
          status: row.status,
          totalPrice: row.totalPrice,
          createdAt: row.createdAt,
          updatedAt: row.updatedAt,
          userId: row.userId
        };

        // 检查 id 是否存在
        if (!order.id) {
          throw new Error("订单 ID 不能为空");
        }

        // 发送请求获取订单详情
        const response = await getOrderTail(order);
        console.log('Order Details:', response.data.data);  // 调试输出

        // 将获取到的订单详情保存并显示
        this.orderDetails = response.data.data;
        this.detailsDialogVisible = true;  // 显示订单详情弹窗
      } catch (error) {
        // 捕获错误并显示提示
        this.$message.error("获取失败");
        console.error("获取订单详情失败：", error);
      }
    },

    formatDate(dateString) {
      const date = new Date(dateString);
      return date.toLocaleDateString(); // 可根据需求修改格式
    },
    getStatusLabel(row,column, cellValue) {
    const statusMap = {
      0: "未派送订单",
      1: "订单未完成",
      2: "订单已完成",
      3: "订单超时"
    };
    return statusMap[cellValue] || "未知状态"; // 使用映射表更简洁
  },
    getmoreStatusLabel(cellValue) {
      switch (cellValue) {
        case 0:
          return "未派送订单";
        case 1:
          return "订单未完成";
        case 2:
          return "订单已完成";
        case 3:
          return "订单超时";
        default:
          return "未知状态"; // 防止未知的状态值
      }
    },
    formatDate(row, column, cellValue) {
      const date = new Date(cellValue);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，需要 +1
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    openDialog(row) {
      // 显示弹窗
      this.dialogVisible = true;
      // 保存当前订单
      this.currentOrder = row;

      // 获取空闲员工数据
      this.fetchSpareEmployees();
    },

    // 获取空闲员工的方法
    async fetchSpareEmployees() {
      try {
        const response = await getSpareEmployee(); // 假设这个 API 是用来获取空闲员工的
        this.spareEmployees = response.data.data;  // 假设返回的员工数据在 response.data.data 中
      } catch (error) {
        console.error("获取空闲员工失败：", error);
      }
    },
    getEmployeeStatus(row, column, cellValue) {
      switch (cellValue) {
        case 0:
          return "不在岗";
        case 1:
          return "在岗";
        case 2:
          return "已接单未完成";
        default:
          return "未知状态"; // 防止未知的状态值
      }
    },
    // 分配员工
    assignEmployee(employee) {
      // 确保当前订单已保存
      if (this.currentOrder) {
        console.log('分配的订单:', this.currentOrder);
        console.log('分配的员工:', employee);

        //调用分配员工的API
        assignOrderToEmployee(this.currentOrder, employee).then(response => {

          // 派单成功后的操作
          this.$message.success("派单成功")
          window.location.reload();
        });
      } else {
        console.error("未选中任何订单");
      }

      // 关闭对话框
      this.dialogVisible = false;
    },
    getAllMoney() {
      getallMoney()
        .then((result) => {
          this.allMoney = result.data.data; // 假设 result.data 包含了总营业额
        })
        .catch((err) => {
          console.error("获取总营业额失败：", err);
        });
    },
    getTodayMoney() {
      gettodayMoney()
        .then((result) => {
          this.todayMoney = result.data.data; // 假设 result.data 包含了总营业额
        })
        .catch((err) => {
          console.error("获取总营业额失败：", err);
        });
    },
    getTodayOrder() {
      gettodayOrder()
        .then((result) => {
          this.todayOrder = result.data.data; // 假设 result.data 包含了总营业额
        })
        .catch((err) => {
          console.error("获取总营业额失败：", err);
        });
    }

  }
}
</script>


<style>
.container {
  display: flex;
  justify-content: space-between;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}
</style>